package com.zkny.zknyerp.config;
/**
 * 重写身份认证类的onAccessDenied，使未登录的用户不在返回url,而是返回json
 */

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


public class MyFormAuthenticationFilter extends FormAuthenticationFilter{
    
	public static boolean isAjax(HttpServletRequest request) {
		String header = request.getHeader("x-requested-with");
		if(header != null && header.equalsIgnoreCase("XMLHttpRequest")) {
			return true;
		}else {
			return false;
		}
	}
	
	@Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setStatus(200);
        httpServletResponse.setContentType("application/json;charset=utf-8");

        //判断是为ajax请求
        if(isAjax((HttpServletRequest) request)) {
        	PrintWriter out = httpServletResponse.getWriter();
            out.flush();
            out.close();
            
        }else {
        	redirectToLogin(request, response);
        }
        
        return false;
    }
}